package com.example.community.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String uri = request.getRequestURI();
        System.out.println("当前访问路径"+uri);

        HttpSession session = request.getSession();
        if (session.getAttribute("currentUser") == null){
            if (uri.contains("/login") || uri.contains("/checkLogin")
                    || uri.indexOf(".jpg") > 0 || uri.indexOf(".jpeg") > 0 || uri.indexOf(".png") > 0
                    || uri.indexOf(".gif") > 0 || uri.indexOf(".css") > 0 || uri.indexOf(".ttf") > 0
                    || uri.indexOf(".js") > 0 || uri.indexOf(".eot") > 0 || uri.indexOf(".svg") > 0
                    || uri.indexOf(".ico") > 0

            ){
                System.out.println("通过");
            }else {
                System.out.println("被拦截");
                response.sendRedirect(request.getContextPath() + "/login");
                return;
            }
        }else {
            System.out.println("通过");
        }

        chain.doFilter(req, resp);
    }
}
